<?php
/**
 * common repository file Created by PhpStorm.
 * User: wumengmeng
 * Date: 2019/09/07
 * Time: 15:23
 */

namespace HiCommon\Repository;

use DB;
use HiCommon\Model\OrderRepairstore;

class OrderRepairstoreRepository extends BaseRepository
{
    public function base_model()
    {
        return new \HiCommon\Model\OrderRepairstore();
    }

    /**
     * 分页获取全部数据
     *
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_all($arr_option = [], array $search = [])
    {
        $model = new OrderRepairstore();
        if (!empty($search['order_type'])) {
            $model = $model->where('order_type', $search['order_type']);
        }
        if (!empty($search['range'])) {
            $range = explode(' - ', $search['range']);
            $model = $model->whereBetween('created_at', [$range[0], $range[1] . ' 23:59:59']);
        }

        return $model->commonget($arr_option);
    }

    /**
     * 分页获取全部数据
     *
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_all_wherein(array $ids, array $arr_option = [])
    {
        return OrderRepairstore::whereIn('shop_id', $ids)->commonget($arr_option);
    }

    /**
     * 分页获取数据
     *
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_list($arr_option = [], array $search = [])
    {
        return OrderRepairstore::where(
            function ($query)
            use ($search) {
                if (!empty($search['order_type'])) {
                    $query->where('order_type', $search['order_type']);
                }
                if (!empty($search['range'])) {
                    $range = explode(' - ', $search['range']);
                    $query->whereBetween('created_at', [$range[0], $range[1] . ' 23:59:59']);
                }
                if (!empty($search['arr_pay_status'])) {
                    $query->whereIn('pay_status', $search['arr_pay_status']);
                }
            })->commonpage($arr_option);
    }

    /**
     * 分页获取数据
     *
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_get_list($arr_option = [], array $arr_search = [])
    {
        $model = new OrderRepairstore();
        if (!empty($arr_search['order_type'])) {
            $model = $model->where('order_type', $arr_search['order_type']);
        }

        if ($arr_search['pay_status'] != '') {
            $model = $model->where('pay_status', $arr_search['pay_status']);
        }
        if ($arr_search['status'] != '') {
            $model = $model->where('status', $arr_search['status']);
        }
        if (!empty($arr_search['date_time'])) {
            $created_at = DB::raw("DATE_FORMAT(created_at,'%Y-%m-%d')");
            $arr_select = ['*', "DATE_FORMAT(created_at,'%Y-%m-%d')"];

            $model = $model->select($arr_select)->where($created_at, $arr_search['date_time']);
        }
        if (!empty($arr_search['user_id'])) {
            $model = $model->where('user_id', $arr_search['user_id']);
        }

        return $model->commonpage($arr_option);
    }

    /**
     * 分页获取售后订单列表
     */
    public function get_sale_order($arr_option = [])
    {
        return OrderRepairstore::where('pay_status', '>', 1)->commonpage($arr_option);
    }

    /**
     * 订单状态
     */
    public function orderStatus($status, $pay_status)
    {
        $state = '';
        if ($pay_status == 0) {
            $state = '待支付';
        } elseif ($pay_status == 1 && $status == 0) {
            $state = '待处理';
        } elseif ($pay_status == 1 && $status == 1) {
            $state = '待确认';
        } elseif ($pay_status == 2) {
            $state = '待退款';
        } elseif ($pay_status == 3) {
            $state = '已退款';
        } elseif ($pay_status == 4) {
            $state = '拒绝退款';
        }

        if ($status == 2) {
            $state = '已取消';
        } elseif ($status == 3) {
            $state = '已评价';
        } elseif ($status == 4) {
            $state = '已完成';
        } elseif ($status == 5) {
            $state = '待评价';
        }

        return $state;
    }

    /**
     *  统计用户的订单信息
     *  hinq 2019 10 25
     *
     **/
    public function get_user_to_order_count(array $arr_where)
    {
        $raw = DB::raw("count('*') as total, sum('pay_amount') as pay_amount , user_id ");
        return OrderRepairstore::select($raw)->where($arr_where)->orderBy('pay_price', 'asc')->with('user')->groupBy('user_id')->get();
    }


    /**
     * 按用户统计数据（商户端用户列表专属）
     *
     * @param array $arr_where
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_user_list(array $arr_where, string $act = 'asc', array $user_ids = [])
    {
        $raw = \DB::raw("count('*') as total, SUM(pay_price) as pay_price , user_id ");
        return OrderRepairstore::select($raw)->where($arr_where)->where(
            function ($query)
            use ($user_ids) {
                if (count($user_ids) > 0 && $user_ids['key_word']) {
                    $query->whereIn('user_id', $user_ids);
                }
            })->orderBy('pay_price', $act)->with('user')->groupBy('user_id')->paginate(15);
    }

    /**
     *  根据商铺分组获取数据
     *
     **/
    public function get_shop_list(array $arr_where)
    {
        $raw = \DB::raw(" shop_id ");
        return OrderRepairstore::select($raw)->where($arr_where)->with('shop')->groupBy('shop_id')->get();
    }


    /**
     * 通过where分页获取数据
     *
     * @param array $arr_where
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_list_by_where($arr_where, $arr_option = [])
    {
        return OrderRepairstore::where($arr_where)->commonpage($arr_option);
    }

    /**
     * 根据条件统计数量
     *
     * @param array $arr_where
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_count_by_where($arr_where)
    {
        return OrderRepairstore::where($arr_where)->count();
    }
    /*
        public function get_count($arr_where)
        {
            return OrderRepairstore::where('order_type', 1)->where($arr_where)->count();
        }*/

    //获取正在进行中的订单
    public function count_order($arr_where)
    {
        return OrderRepairstore::where($arr_where)->where('status', '<=', 1)->where('pay_status', '<=', 1)->count();
    }

    //售后订单数量
    public function count_sale_order($arr_where)
    {
        return OrderRepairstore::where($arr_where)->where('status', 0)->where('pay_status', '>', 1)->count();
    }


    //售后订单数量
    public function count_by_where($arr_where)
    {
        return OrderRepairstore::where($arr_where)->whereIn('status' , ['0'])->count();
    }

    /**
     * 根据条件统计总和
     *
     * @param array $arr_where
     * @param string $s_field
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_sum_by_where($arr_where = [], $s_field = 'mark')
    {
        return OrderRepairstore::where($arr_where)->sum($s_field);
    }

    /**
     * 根据条件批量删除信息
     *
     * @param array $arr_where
     * @param bool $method
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function delete_by_where($arr_where = [], $method = false)
    {
        return OrderRepairstore::where($arr_where)->commondelete($method);
    }

    /**
     * 通过where获取一条数据
     *
     * @param array $arr_where
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_one_by_where($arr_where, $arr_option = [])
    {
        return OrderRepairstore::where($arr_where)->commonfirst($arr_option);
    }

    /**
     * 添加一条数据
     *
     * @param array $arr_input
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function add_one($arr_input)
    {
        return OrderRepairstore::create($arr_input);
    }

    /**
     * 添加多条数据
     *
     * @param array $arr_data
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function add_many($arr_data)
    {
        return OrderRepairstore::insert($arr_data);
    }

    /**
     * 查询一条数据
     *
     * @param int $n_id
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_one(int $n_id, $arr_option = [])
    {
        return OrderRepairstore::commonfind($n_id, $arr_option);
    }

    public function find_one(array $map)
    {
        return OrderRepairstore::where($map)->first();
    }

    /**
     * 更新或新建一条数据
     *
     * @param $arr_where
     * @param $arr_input
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function edit_or_create($arr_where, $arr_input)
    {
        $res = OrderRepairstore::where($arr_where)->first();
        if (is_null($res)) {
            OrderRepairstore::create(array_merge($arr_where, $arr_input));
        } else {
            OrderRepairstore::where($arr_where)->update($arr_input);
        }
        return OrderRepairstore::where($arr_where)->first();
    }

    /**
     * 修改一条数据
     *
     * @param array $arr_input
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function edit_one(array $arr_input)
    {
        return OrderRepairstore::where('id', $arr_input['id'])->update($arr_input);
    }


    /**
     * 根据条件更新数据
     */
    public function edit_one_whereIn(array $map, array $arr_input)
    {
        return OrderRepairstore::whereIn($map['key'] , $map['value'])->update($arr_input);
    }


    /**
     * 删除一条数据
     *
     * @param int $n_id
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function delete_one(int $n_id)
    {
        return OrderRepairstore::where('id', $n_id)->commondelete();
    }

    /**
     * 修改一条数据状态
     *
     * @param int $n_id
     * @param int $n_state
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function change_one_state(int $n_id, int $n_state)
    {
        return OrderRepairstore::where('id', $n_id)->update(['status' => $n_state]);
    }

    /**
     * 字段自增
     *
     * @param int $n_id
     * @param string $s_field
     * @param int $n_step
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function increase_num($n_id, $s_field = 'commend_num', $n_step = 1)
    {
        return OrderRepairstore::where('id', $n_id)->increment($s_field, $n_step);
    }

    /**
     * 字段自减
     *
     * @param int $n_id
     * @param string $s_field
     * @param int $n_step
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function decrease_num($n_id, $s_field = 'commend_num', $n_step = 1)
    {
        return OrderRepairstore::where('id', $n_id)->decrement($s_field, $n_step);
    }

    /**
     * 检查用户是否已经有该订单
     */
    public function check_is_have(array $map)
    {
        return OrderRepairstore::where($map)->with(['shop', 'goods'])->orderBy('id', 'desc')->first();
    }

    /**
     * 更新订单支付状态
     */
    public function edit_pay_status(array $map, array $arr_input)
    {
        return OrderRepairstore::where($map)->update($arr_input);
    }

    /**
     * 根据条件统计订单数量(最近一周)(公众号)
     */
    public function count_by_where_days(int $shop_id, array $dayArray)
    {
        $raw = DB::raw("count(1) as total, DATE_FORMAT(created_at,'%Y-%m-%d') as date, sum(pay_price) as amount");
        $between = [reset($dayArray), end($dayArray) . ' 23:59:59'];
        //自驾订单统计
        $days[1] = OrderRepairstore::select($raw)
            ->whereBetween('created_at', $between)
            ->where(['shop_id' => $shop_id, 'order_type' => 1])
            ->groupBy('date')
            ->get()->toArray();

        //代驾订单统计
        $days[2] = OrderRepairstore::select($raw)
            ->whereBetween('created_at', $between)
            ->where(['shop_id' => $shop_id, 'order_type' => 2])
            ->groupBy('date')
            ->get()->toArray();

        //总共的订单数
        $days[3] = OrderRepairstore::whereBetween('created_at', $between)
            ->where(['shop_id' => $shop_id])
            ->count();

        return $days;
        /*$results = \DB::select("SELECT DATE_FORMAT(created_at,'%Y-%m-%d') as day_time ,count(*) as num FROM car_order_repairstore
                        where shop_id = " . $data['shop_id'] . " and created_at BETWEEN  '".$dayArray[1]."' and '".$dayArray[7]."' and deleted_at is null  GROUP BY  day_time");*/
    }

    /**
     * 根据条件统计订单数量（最近7个月）(公众号)
     */
    public function count_by_where_month(int $shop_id, array $monthArray)
    {
        $raw = DB::raw("count(1) as total, DATE_FORMAT(created_at,'%Y-%m') as date, sum(pay_price) as amount");
        $between = [reset($monthArray), date('Y-m-d H:i:s', time())];
        //自驾订单统计 2020 01 10 (服务订单)改
        $month[1] = OrderRepairstore::select($raw)
            ->whereBetween('created_at', $between)
            ->where(['shop_id' => $shop_id, 'order_type' => 1])
            ->groupBy('date')
            ->get()->toArray();

        //代驾订单统计 2020 01 10 (保养订单)改
        $month[2] = OrderRepairstore::select($raw)
            ->whereBetween('created_at', $between)
            ->where(['shop_id' => $shop_id, 'order_type' => 2])
            ->groupBy('date')
            ->get()->toArray();

        //总共的订单数
        $month[3] = OrderRepairstore::whereBetween('created_at', $between)
            ->where(['shop_id' => $shop_id])
            ->count();
        return $month;
    }


    /**
     * 通过条件查询所有可自动取消的订单(定时任务)
     */
    public function all_auto_cancel_order($arr_select = ['*'], $n_minutes = 30)
    {
        $arr_where = ['status' => 0, 'pay_status' => 0, 'is_online_pay' => 0];
        $s_time = time_to_ymdhis(time() - 60 * $n_minutes);

        return OrderRepairstore::where($arr_where)->where('created_at', '<', $s_time)->select($arr_select)->get();
    }

    /**
     * 通过条件查询所有可关闭的订单(定时任务)
     */
    public function all_confirm_order_repair()
    {
        $date = date('Y-m-d', strtotime("-3 day"));//3天前日期
        //$date = date('Y-m-d');
        $checked_at = DB::raw("DATE_FORMAT(checked_at,'%Y-%m-%d')");
        return OrderRepairstore::where($checked_at, $date)
            ->where(['status' => 1, 'is_finish' => 2])
            ->select(['id', 'is_finish', 'checked_at'])
            ->get()
            ->toArray();
    }

    /**
     * 通过条件查询所有可自动退款的订单(定时任务)
     */
    public function api_auto_repair_refund($arr_select = ['*'], $n_day = 7)
    {
        $s_time = time_to_ymdhis(time() - 60 * 60 * 24 * $n_day);

        return OrderRepairstore::where('status', 0)->where('created_at', '<', $s_time)->whereBetween('pay_status', [1, 2])->select($arr_select)->get();
    }

    /**
     * 根据条件更新数据
     * @param array $orderIds
     * @param array $up_data
     * @return mixed
     */
    public function update_by_where_in($orderIds = [], $up_data = [])
    {
        return OrderRepairstore::whereIn('id', $orderIds)->update($up_data);
    }

    /**
     *  根据条件获取数量（开发票时检测当前订单是否可以开票）
     *  hinq 2020 6 15
     *
     **/
    public function get_count_whereIn( array $arr_whereIn = ['key'=>'id','value'=>[]]){
        return OrderRepairstore::whereIn($arr_whereIn['key'], $arr_whereIn['value'])->whereIn('is_invoice',[1,2])->count();
    }

}